package com.msk.base.service;


import com.msk.base.domain.goods.Goods;
import com.msk.base.domain.goodsMember.GoodsMember;
import com.msk.base.service.goods.GoodsService;
import com.msk.base.service.goodsMember.GoodsMemberService;
import com.msk.common.utils.IdGen;
import com.msk.common.utils.StringUtils;
import com.msk.sys.utils.DocUtils;
import com.msk.sys.utils.PdfUtil;
import com.msk.sys.utils.SystemPath;
import com.msk.third.service.OssServerService;
import com.msk.wlhy.domain.HtDriverFile;
import com.msk.wlhy.domain.HtLogisticsOrder;
import com.msk.wlhy.domain.HtLogisticsOrderDetail;
import com.msk.wlhy.domain.HtSupplier;
import com.msk.wlhy.service.HtDriverFileService;
import com.msk.wlhy.service.HtLogisticsOrderDetailService;
import com.msk.wlhy.service.HtLogisticsOrderService;
import com.msk.wlhy.service.HtSupplierService;
import jdk.nashorn.internal.objects.Global;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @desc: 用于生成货物运输合同服务
 * @author: zlf
 * @date: 2020-11-06 11:56
 **/
@Service
@Transactional(readOnly = true)
public class GenerateContractService {

    private static Logger log = LoggerFactory.getLogger(GenerateContractService.class);

    @Autowired
    private HtLogisticsOrderService htLogisticsOrderService;

    @Autowired
    private HtLogisticsOrderDetailService htLogisticsOrderDetailService;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private GoodsMemberService goodsMemberService;

    @Autowired
    private HtSupplierService htSupplierService;

    @Autowired
    private HtDriverFileService htDriverFileService;

    @Autowired
    private OssServerService ossServerService;

    /**
     * 生成平台和货主合同
     * @param id
     */
    @Transactional(readOnly = false)
    public void generatePurchaseContract(String id) {
        HtLogisticsOrder htLogisticsOrder = htLogisticsOrderService.get(id);
        if (htLogisticsOrder == null) {
            return;
        }
        Map<String, Object> param = new HashMap<>();
        String priceType = "";
        if (htLogisticsOrder.getGoods() != null) {
            Goods goods = goodsService.get(htLogisticsOrder.getGoods().getId());
            if (goods != null) {
                priceType = goods.getPriceType();
                param.put("goodsCode", goods.getCode());
            }
        }
        GoodsMember goodsMember = goodsMemberService.getByCompany1Id(htLogisticsOrder.getConsigner());
        if (goodsMember != null) {
            param.put("firstParty", goodsMember.getComName());
            param.put("firstAddress", StringUtils.getString(dealSpcString(goodsMember.getGmAreaName()) + goodsMember.getDetailAddress()));
        }
        param.put("secondParty", "陕西推诚新能源科技有限公司");
        param.put("secondAddress", "陕西省榆林市府谷县府谷镇花石峁村府店公路149号");
        if ("0".equals(priceType)) {
            BigDecimal unitPrice = new BigDecimal(htLogisticsOrder.getTransportPrice()).setScale(2, RoundingMode.DOWN);
            param.put("money", "单价为" + unitPrice + "元");
        } else if ("1".equals(priceType)){
            BigDecimal totalPrice = new BigDecimal(htLogisticsOrder.getAllFreight()).setScale(2, RoundingMode.DOWN);
            param.put("money", "总价为" + totalPrice + "元");
        }
        if (!param.containsKey("contractNo")) {
            param.put("contractNo", htLogisticsOrder.getOrderNo());
        }
        param.put("name", htLogisticsOrder.getGoodsName());
        param.put("startPlace", dealSpcString(htLogisticsOrder.getStartAreaName()));
        param.put("endPlace", dealSpcString(htLogisticsOrder.getEndAreaName()));
        Date createDate = htLogisticsOrder.getCreateDate();
        Calendar cal = Calendar.getInstance();
        if (createDate != null) {
            cal.setTime(createDate);
        }
        param.put("year", Integer.toString(cal.get(Calendar.YEAR)));//年
        param.put("month", cal.get(Calendar.MONTH) + 1);//月
        param.put("day", cal.get(Calendar.DAY_OF_MONTH));//日
        String fileName = IdGen.uuid();
        String docPath = getTemporary() + "/" + fileName + ".doc";
        DocUtils docUtil = new DocUtils();
        String ftlName = "contract";
        //填充模板数据,并生成doc文件
        boolean flag = docUtil.createDocNew(param, ftlName, docPath);
        if (flag) {
            String pdfPath = PdfUtil.wordToPdf(docPath);
            try {
                docPath = ossServerService.uploadFile2Oss(new File(docPath),fileName + ".doc");
                pdfPath = ossServerService.uploadFile2Oss(new File(pdfPath),fileName + ".pdf");
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (StringUtils.isBlank(pdfPath)) {
                log.info("生成平台和货主合同word转pdf失败");
                return;
            }
            //第二步
            File unsignFile = new File(pdfPath);
            if (unsignFile == null) {
                log.info("生成平台和货主合同为空word转pdf失败");
                return;
            }
            HtLogisticsOrder htLogisticsOrderUpd = new HtLogisticsOrder();
            htLogisticsOrderUpd.setId(htLogisticsOrder.getId());
            htLogisticsOrderUpd.setPlatOwnerDocFile(docPath);
            htLogisticsOrderUpd.setPlatOwnerPdfFile(pdfPath);
            htLogisticsOrderUpd.preUpdate();
            htLogisticsOrderService.updateInfoById(htLogisticsOrderUpd);
            log.info("生成平台和货主合同成功");
        } else {
            log.info("生成平台和货主合同失败");
        }
    }

    /**
     * 生成平台和承运商合同
     * @param detailId
     */
    @Transactional(readOnly = false)
    public void generateSupplierContract(String detailId) {
        HtLogisticsOrderDetail htLogisticsOrderDetail = htLogisticsOrderDetailService.get(detailId);
        if (htLogisticsOrderDetail == null) {
            return;
        }
        String orderId = htLogisticsOrderDetail.getOrderId();
        HtLogisticsOrder htLogisticsOrder = htLogisticsOrderService.get(orderId);
        if (htLogisticsOrder == null) {
            return;
        }
        Map<String, Object> param = new HashMap<>();
        String priceType = "";
        if (htLogisticsOrder.getGoods() != null) {
            Goods goods = goodsService.get(htLogisticsOrder.getGoods().getId());
            if (goods != null) {
                priceType = goods.getPriceType();
                param.put("goodsCode", goods.getCode());
            }
        }
        param.put("firstParty", "陕西推诚新能源科技有限公司");
        param.put("firstAddress", "陕西省榆林市府谷县府谷镇花石峁村府店公路149号");
        HtSupplier supplier = htLogisticsOrderDetail.getSupplier();
        if (supplier == null) {
            return;
        }
        HtSupplier htSupplier = htSupplierService.get(htLogisticsOrderDetail.getSupplier());
        if (htSupplier != null) {
            param.put("secondParty", htSupplier.getName());
            param.put("secondAddress", StringUtils.getString(dealSpcString(htSupplier.getSiteName()) + htSupplier.getDetailAddress()));
        } else if (StringUtils.isNotBlank(supplier.getId())) {
            String secondParty = "";
            String secondAddress = "";
            HtDriverFile htDriverFile = htDriverFileService.get(supplier.getId());
            if (htDriverFile != null) {
                secondParty = htDriverFile.getName();
            }
            param.put("secondParty", secondParty);
            param.put("secondAddress", secondAddress);
        } else {
            return;
        }
        if ("0".equals(priceType)) {
            BigDecimal unitPrice = new BigDecimal(htLogisticsOrderDetail.getPrice()).setScale(2, RoundingMode.DOWN);
            param.put("money", "单价为" + unitPrice + "元");
        } else if ("1".equals(priceType)){
            BigDecimal totalPrice = new BigDecimal(htLogisticsOrderDetail.getRevicePrice()).setScale(2, RoundingMode.DOWN);
            param.put("money", "总价为" + totalPrice + "元");
        }
        if (!param.containsKey("contractNo")) {
            param.put("contractNo", htLogisticsOrderDetail.getOriginalNumber());
        }
        param.put("name", htLogisticsOrder.getGoodsName());
        param.put("startPlace", dealSpcString(htLogisticsOrder.getStartAreaName()));
        param.put("endPlace", dealSpcString(htLogisticsOrder.getEndAreaName()));
        Date createDate = htLogisticsOrderDetail.getCreateDate();
        Calendar cal = Calendar.getInstance();
        if (createDate != null) {
            cal.setTime(createDate);
        }
        param.put("year", Integer.toString(cal.get(Calendar.YEAR)));//年
        param.put("month", cal.get(Calendar.MONTH) + 1);//月
        param.put("day", cal.get(Calendar.DAY_OF_MONTH));//日
        String fileName = IdGen.uuid();
        String docPath = getTemporary() + "/" + fileName + ".doc";
        DocUtils docUtil = new DocUtils();
        String ftlName = "contract";
        //填充模板数据,并生成doc文件
        boolean flag = docUtil.createDocNew(param, ftlName, docPath);
        if (flag) {
            String pdfPath = PdfUtil.wordToPdf(docPath);
            try {
                docPath = ossServerService.uploadFile2Oss(new File(docPath),fileName + ".doc");
                pdfPath = ossServerService.uploadFile2Oss(new File(pdfPath),fileName + ".pdf");
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (StringUtils.isBlank(pdfPath)) {
                log.info("生成平台和承运商合同word转pdf失败");
                return;
            }
            //第二步
            File unsignFile = new File(pdfPath);
            if (unsignFile == null) {
                log.info("生成平台和承运商合同为空word转pdf失败");
                return;
            }
            HtLogisticsOrderDetail htLogisticsOrderDetailUpd = new HtLogisticsOrderDetail();
            htLogisticsOrderDetailUpd.setId(htLogisticsOrderDetail.getId());
            htLogisticsOrderDetailUpd.setPlatSupplierDocFile(docPath);
            htLogisticsOrderDetailUpd.setPlatSupplierPdfFile(pdfPath);
            htLogisticsOrderDetailUpd.preUpdate();
            htLogisticsOrderDetailService.updateInfoById(htLogisticsOrderDetailUpd);
            log.info("生成平台和承运商合同成功");
        } else {
            log.info("生成平台和承运商合同失败");
        }
    }

    /**
     * 获取临时目录
     * @return
     */
    private static String getTemporary(){
        String classesPath = SystemPath.getJavaClassPath();
        String prePath = classesPath.replace("/WEB-INF/classes/","");
        if (!prePath.endsWith("/")) {
            prePath = prePath + "/";
        }
        String filePath = prePath + "/userfiles/".substring(1) +  DateFormatUtils.format(new Date(), "yyyyMM");
        File file = new File(filePath);
        if(!file.exists()){
            file.mkdirs();
        }
        return filePath;
    }

    private String dealSpcString(String str) {
        if (StringUtils.isBlank(str)) {
            return "";
        } else {
            str = str.replaceAll("-","");
        }
        return str;
    }

    /**
     * 获取保存路径
     * @param path
     * @return
     */
    private String getSavePath(String path) {
        if (StringUtils.isNotBlank(path)) {
            path = path.substring(path.indexOf("userfiles"));
        }
        return path;
    }
}
